<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!isset($_GET['comment_id'])){
    exit();
}

$article_id = $_GET['comment_id'];

if (!isset($_COOKIE['token'])) {
    //header('Location: login_form.html');
    // 获取文章总点赞数
    $query = $conn->prepare("SELECT COUNT(*) as like_count FROM comment_likes WHERE comment_id = ?");
    $query->bind_param("i", $article_id);
    $query->execute();
    $result = $query->get_result();
    $like_count = $result->fetch_assoc()['like_count'];
    $query->close();

    echo json_encode(['like_count' => $like_count]);
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

$comment_id = $_GET['comment_id'];

$query = $conn->prepare("SELECT COUNT(*) as liked FROM comment_likes WHERE comment_id = ? AND user_id = ?");
$query->bind_param("ii", $comment_id, $user_id);
$query->execute();
$result = $query->get_result();
$liked = $result->fetch_assoc()['liked'] > 0;
$query->close();

$query = $conn->prepare("SELECT COUNT(*) as like_count FROM comment_likes WHERE comment_id = ?");
$query->bind_param("i", $comment_id);
$query->execute();
$result = $query->get_result();
$like_count = $result->fetch_assoc()['like_count'];
$query->close();

echo json_encode(['liked' => $liked, 'like_count' => $like_count]);

$conn->close();
?>